#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <wiringPi.h>

int read_bit(int pin)
{
    while(digitalRead(pin)==LOW);
    delayMicroseconds(28);
    if(digitalRead(pin)==LOW)
    {
        return 0;
    }
    int t1 = time(NULL);
    while(digitalRead(pin)==HIGH)
    {
        if(time(NULL)-t1)
        {
            return 2;
        }
    }
    return 1;
}

int read_byte(int pin)
{
    int byte = 0;
    for(int i=0;i<8;i++)
    {
        int res =  read_bit(pin);
        if(res == 2)
        {
            return -1;
        }
        byte <<= 0x01;
        byte |= res;
    }
    return byte;
}

void dht11_init()
{
    if(wiringPiSetupGpio()<0)
    {
        printf("初始化失败\n");
    }
}

int read_dht(int pin,int* data)
{
    while(1)
    {

        //开始信号
        pinMode(pin,OUTPUT);
        delayMicroseconds(140);

        digitalWrite(pin,HIGH);
        delayMicroseconds(140);
        digitalWrite(pin,LOW);
        delay(18);
        digitalWrite(pin,HIGH);
        delayMicroseconds(40);

        pinMode(pin,INPUT);
        if(digitalRead(pin) == LOW)
        {
            //读取数据
            while(digitalRead(pin)==LOW);
            while(digitalRead(pin)==HIGH);

            for(int i=0;i<5;i++)
            {
                data[i] = read_byte(pin);
                if(data[i] <0)
                {
                    //printf("读取超时...\n");
                    return 2;
                }
            }
            pinMode(pin,OUTPUT);
            digitalWrite(pin,HIGH);
            delayMicroseconds(140);

            if(data[4] == data[0]+data[1]+data[2]+data[3])
            {
                // printf("湿度:%d.%d %%RH\n",data[0],data[1]);
                // printf("温度:%d.%d ℃\n",data[2],data[3]);
                return 1;
            }
            else
            {
                //printf("校验和错误\n");
                return 0;
            }

            //结束信号
        }
        else
        {
            //printf("未响应...\n");
            return 3;
        }
        sleep(1);
    }
}